package com.huanglejing.shanggou.activity

import android.os.Bundle
import android.support.v4.util.ArrayMap
import android.support.v7.widget.GridLayoutManager
import android.text.Editable
import android.text.TextWatcher
import android.util.Log
import android.view.View
import android.view.inputmethod.EditorInfo
import com.huanglejing.mylibrary.KLog
import com.huanglejing.shanggou.R
import com.huanglejing.shanggou.adapter.ProductListAdapter
import com.huanglejing.shanggou.bean.NewComeProBean
import com.huanglejing.shanggou.common.AppBaseActivity
import com.huanglejing.shanggou.common.AppContext
import com.huanglejing.shanggou.data.CacheCustomerId
import com.huanglejing.shanggou.data.beanDao
import com.huanglejing.shanggou.data.getCacheGoods
import com.huanglejing.shanggou.greendao.CacheGoodsBean
import com.huanglejing.shanggou.interfaces.SearchContract.SearchPresenter
import com.huanglejing.shanggou.interfaces.SearchContract.SearchView
import com.huanglejing.shanggou.presenterimpl.SearchImpl
import com.huanglejing.shanggou.utils.ToastUtils
import com.huanglejing.shanggou.utils.UIHelper
import com.huanglejing.shanggou.utils.checkEmpty
import com.jcodecraeer.xrecyclerview.ProgressStyle
import kotlinx.android.synthetic.main.activity_search.*
import rx.Observable

class SearchActivity : AppBaseActivity<SearchPresenter<SearchView>, SearchView>(), SearchView {
    private var queryWords: String? = ""
    private var searchWords: String? = ""
    private var mData: ArrayList<NewComeProBean>? = arrayListOf()
    private var leftPosion = 0
    private var rightPosion = 0
    private var mNextAdapter: ProductListAdapter? = null
    private var categoryId = ""
    private var isLoadComplete = false

    private val mEmptyView by lazy {
        mRootView?.findViewById<View>(R.id.ll_xr_empty)
    }
    private val mErrorView by lazy {
        mRootView?.findViewById<View>(R.id.ll_xr_error)
    }
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        searchWords = intent?.extras?.getString("searchWords", "")
        initWidget()
    }

    override fun getRequestParams(): Observable<Map<String, Any>> {
        val map = ArrayMap<String, String>().apply {
            put("companyId", AppContext.get().companyId)
            put("q", queryWords)
        }
        return Observable.just(map)
    }

    private fun initWidget() {
//        xr_search_list.visibility = View.GONE

        tv_search_cancle?.setOnClickListener {
            finish()
        }
        et_search?.setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                //完成自己的事件
                queryWords = et_search?.text?.toString()

                if (queryWords.checkEmpty()){
                    ToastUtils.toastLong(resources.getString(R.string.str_search_words_not_null))
                    return@setOnEditorActionListener false
                }
                mBasePresenter?.getSearchList()
            }
            return@setOnEditorActionListener false
        }
        et_search?.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(s: Editable?) {
                queryWords = et_search?.text?.toString()?:""
                et_search?.setSelection(queryWords?.length?:0)
            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }
        })
        iv_home_scan.setOnClickListener {
            UIHelper.startActivity(SweepSearchActivity::class.java)
        }
      
        xr_search_list?.setPullRefreshEnabled(false)
        xr_search_list?.setLoadingMoreEnabled(false)
        //设置加载风格
        xr_search_list?.setLoadingMoreProgressStyle(ProgressStyle.LineScale)
        xr_search_list?.setRefreshProgressStyle(ProgressStyle.BallGridPulse)

        val manager = GridLayoutManager(this@SearchActivity, 2)
        xr_search_list?.layoutManager = manager
        mNextAdapter = ProductListAdapter(this@SearchActivity, mData ?: arrayListOf())
        xr_search_list?.adapter = mNextAdapter
        var loadAll = getCacheGoods()?.filter { it.companyId?.equals(AppContext.get().companyId?:"")?:false }
        mNextAdapter?.setCacheData(loadAll)
        mNextAdapter?.setOnItemClickListener(object : ProductListAdapter.OnItemClickListener {
            override fun onItemClick(v: View?, position: Int) {
                val bundle = Bundle()
                bundle.putString("categoryId", mData?.get(position)?.parentGuid)
                bundle.putInt("position", position)
                bundle.putInt("leftPosion", leftPosion)
                bundle.putInt("rightPosion", rightPosion)
                bundle.putString("mBundleData", AppContext.gson().toJson(mData))
                UIHelper.startActivity(ProListDetailActivity::class.java, bundle)
            }
        })
        mNextAdapter?.setCacheOrderBeanListener(object : ProductListAdapter.CacheOrderBeanListener {
            override fun onCacheOrderBeanAdd(position: Int, selectNum: Int, bean: NewComeProBean?) {
                var loadAll = getCacheGoods()?.filter { it.companyId?.equals(AppContext.get().companyId?:"")?:false }
                var isUpdate = false
                var updateBean: CacheGoodsBean? = null
                loadAll?.forEachIndexed { index, orderBean ->
                    if (orderBean?.goodNO?.equals(bean?.id ?: "") ?: false) {
                        isUpdate = true
                        updateBean = orderBean
                    }
                }
                if (isUpdate && updateBean != null) {
                    updateBean?.goodNO = bean?.id ?: ""
                    updateBean?.companyId = AppContext.get()?.companyId ?: ""
                    updateBean?.customerId = CacheCustomerId ?: ""
                    updateBean?.bz = updateBean?.bz ?: ""
                    updateBean?.categoryGUID = categoryId ?: ""
                    updateBean?.num = selectNum?.toString() ?: "0"
                    updateBean?.price = bean?.price ?: ""
                    updateBean?.bagCount = bean?.bagCount ?: ""
                    updateBean?.boxCount = bean?.boxCount ?: ""
                    updateBean?.count = bean?.count ?: ""
                    updateBean?.name = bean?.name ?: ""
                    updateBean?.no = bean?.no ?: ""
                    updateBean?.parentGuid = bean?.parentGuid ?: ""
                    updateBean?.url = bean?.url ?: ""
                    updateBean?.xname = bean?.xname ?: ""
                    updateBean?.zk = bean?.zk ?: ""
                    val zhekou = bean?.zk?.toDoubleOrNull()?.div(100) ?: 0.00
                    updateBean?.totalPrice = bean?.price?.toDoubleOrNull()?.times(selectNum)?.times(1.minus(zhekou))?.toString() ?: ""
                    beanDao?.update(updateBean)
                } else if (!isUpdate && updateBean == null) {
                    updateBean = CacheGoodsBean()
                    updateBean?.goodNO = bean?.id ?: ""
                    updateBean?.companyId = AppContext.get()?.companyId ?: ""
                    updateBean?.customerId = CacheCustomerId ?: ""
                    updateBean?.bz = ""
                    updateBean?.categoryGUID = categoryId ?: ""
                    updateBean?.num = selectNum?.toString() ?: "0"
                    updateBean?.price = bean?.price ?: ""
                    updateBean?.bagCount = bean?.bagCount ?: ""
                    updateBean?.boxCount = bean?.boxCount ?: ""
                    updateBean?.count = bean?.count ?: ""
                    updateBean?.name = bean?.name ?: ""
                    updateBean?.no = bean?.no ?: ""
                    updateBean?.parentGuid = bean?.parentGuid ?: ""
                    updateBean?.url = bean?.url ?: ""
                    updateBean?.xname = bean?.xname ?: ""
                    updateBean?.zk = bean?.zk ?: ""
                    val zhekou = bean?.zk?.toDoubleOrNull()?.div(100) ?: 0.00
                    updateBean?.totalPrice = bean?.price?.toDoubleOrNull()?.times(selectNum)?.times(1.minus(zhekou))?.toString() ?: ""
                    beanDao?.insert(updateBean)
                }

            }

            override fun onCacheOrderBeanMinius(position: Int, selectNum: Int, bean: NewComeProBean?) {
                var loadAll = getCacheGoods()?.filter { it.companyId?.equals(AppContext.get().companyId?:"")?:false }
                var isUpdate = false
                var updateBean: CacheGoodsBean? = null
                loadAll?.forEachIndexed { index, orderBean ->
                    if (orderBean?.goodNO?.equals(bean?.id ?: "") ?: false) {
                        isUpdate = true
                        updateBean = orderBean
                    }
                }
                if (isUpdate && updateBean != null && selectNum > 0) {
                    updateBean?.goodNO = bean?.id ?: ""
                    updateBean?.companyId = AppContext.get()?.companyId ?: ""
                    updateBean?.customerId = CacheCustomerId ?: ""
                    updateBean?.bz = updateBean?.bz ?: ""
                    updateBean?.categoryGUID = categoryId ?: ""
                    updateBean?.num = selectNum?.toString() ?: "0"
                    updateBean?.price = bean?.price ?: ""
                    updateBean?.bagCount = bean?.bagCount ?: ""
                    updateBean?.boxCount = bean?.boxCount ?: ""
                    updateBean?.count = bean?.count ?: ""
                    updateBean?.name = bean?.name ?: ""
                    updateBean?.no = bean?.no ?: ""
                    updateBean?.parentGuid = bean?.parentGuid ?: ""
                    updateBean?.url = bean?.url ?: ""
                    updateBean?.xname = bean?.xname ?: ""
                    updateBean?.zk = bean?.zk ?: ""
                    updateBean?.totalPrice = bean?.price?.toDoubleOrNull()?.times(selectNum)?.toString() ?: ""
                    beanDao?.update(updateBean)
                } else if (isUpdate && updateBean != null && selectNum == 0) {
                    beanDao?.delete(updateBean)
                }

            }
        })
        manager.spanSizeLookup = object : GridLayoutManager.SpanSizeLookup() {
            override fun getSpanSize(position: Int): Int {
                if (xr_search_list?.isHeaderView(position) == true) {
                    Log.d("isHeader", "isHeader  true    $position    type  ")
                    return 2
                } else if (xr_search_list?.isFooterView(position) == true) {
                    return 2
                } else if (xr_search_list?.isEmptyView(mNextAdapter?.itemCount ?: 0) == true) {
                    return 2
                } else {
                    Log.d("isHeader", "isHeader  false    $position    type  ")
                    return 1
                }
            }
        }
    }

    override fun onResume() {
        super.onResume()
        if (!searchWords.checkEmpty()){
            et_search?.setText(searchWords)
            mBasePresenter?.getSearchList()
        }
    }
    override fun <T> showContent(data: T?) {
        try {
            if (data as? ArrayList<NewComeProBean> != null) {
                mData?.clear()
                mData?.addAll((data as? ArrayList<NewComeProBean>) ?: arrayListOf())
                if (mData?.size?:0<1 && mEmptyView!=null){
                    xr_search_list?.emptyView=mEmptyView
                }
                mNextAdapter?.setData(mData)
                loadComPlete()
            }
        } catch (e: Exception) {
            KLog.e(e.message)
        }

    }

    override fun showError(e: Throwable?) {
        KLog.e(e?.message)
        if (mErrorView!=null){
            xr_search_list?.emptyView=mErrorView
            mErrorView?.setOnClickListener {
                mBasePresenter?.getSearchList()
            }
        }
        mNextAdapter?.setData(arrayListOf())
        loadComPlete()
    }

    fun loadComPlete() {
        xr_search_list?.loadMoreComplete()
        xr_search_list?.refreshComplete()
        if (!isLoadComplete) {
            xr_search_list?.setNoMore(false)
        } else {
            xr_search_list?.setNoMore(true)
        }

    }

    override fun createPresenter(): SearchPresenter<SearchView> = SearchImpl()

    override fun getLayoutId(): Int = R.layout.activity_search

    override fun requestPermission() {
    }


}
